package com.abe.mvp.view.fragment;

import java.util.ArrayList;
import java.util.List;

import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.abe.config.Constants;
import com.abe.mvp.model.bean.exercise.ExerciseGroupBean;
import com.abe.mvp.model.bean.exercise.ExerciseNodeBean;
import com.abe.mvp.view.activity.FragmentCallbackListener.CallbackListener;
import com.abe.mvp.view.fragment.base.BaseExerciseFragment;
import com.abe.threadmill.R;
import com.abe.utils.NormalUtils;
import com.abe.utils.ThreadPoolUtils;
import com.abe.view.XSeekBar;
import com.abe.view.XSeekBar.OnXSeekBarListener;

public class ExerciseTargetFragment extends BaseExerciseFragment implements
		OnXSeekBarListener {

	private CallbackListener callback;
	/** 锻炼标识 */
	private boolean is_run = false;
	/** 目标类型标识 */
	private int target_type_pos;
	private int[] targets = { R.string.common_time, R.string.common_distance,
			R.string.common_calorie };
	private int[] targets_unit = { R.string.common_time_unit,
			R.string.common_distance_unit, R.string.common_calorie_unit };
	/** 范围:倒计时（分钟），距离单位（0.01Km），卡路里（kcal） */
	private int max[] = { 100, 10000, 3000 };
	/** 选中对应目标最大值 */
	private int currentMax = 0;
	/** 拖动百分比 */
	private int progress = 0;
	/** 确定目标值 */
	private int currentNum = 0;
	/** 累计完成值 */
	private int cumulativeNum = 0;
	private List<ExerciseNodeBean> nodeList;

	@ViewInject(R.id.target_text_name)
	private TextView target_text_name;
	@ViewInject(R.id.target_text_num)
	private TextView target_text_num;

	@ViewInject(R.id.target_layout_setting)
	private LinearLayout target_layout_setting;
	@ViewInject(R.id.target_button_reduce)
	private Button target_button_reduce;
	@ViewInject(R.id.target_seekbar_change_num)
	private XSeekBar target_seekbar_change_num;
	@ViewInject(R.id.target_button_plus)
	private Button target_button_plus;

	@ViewInject(R.id.show_test_info)
	private TextView show_test_info;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		callback = (CallbackListener) getActivity();
		View view = this.onCreateView(inflater,
				R.layout.activity_tm_tab_target, container, savedInstanceState);
		initView(view);
		callback.fragmentReady();
		return view;
	}

	public void initView(View view) {
		target_seekbar_change_num.setProgressWeight((int)(30*scale));
		target_seekbar_change_num.setMaxWeight((int)(30*scale));
		target_seekbar_change_num.setRadius((int)(45*scale));

		is_run = false;
		allow_change_in_running = true;
		target_seekbar_change_num.setOnSeekBarListener(this);
		current_speed = Constants.SpeedConvertByKMH(Constants.SpeedStart);
		current_slope = 0;
		old_speed = current_speed;
		old_slope = current_slope;
	}

	@Event(value = R.id.target_button_reduce, type = View.OnClickListener.class)
	private void seekbarReduce(View view) {
		/** 减百分之一 */
		if (progress > 0) {
			target_seekbar_change_num.setProgress(progress - 1);
		}
	}

	@Event(value = R.id.target_button_plus, type = View.OnClickListener.class)
	private void seekbarPlus(View view) {
		/** 增百分之一 */
		if (progress < 100) {
			target_seekbar_change_num.setProgress(progress + 1);
		}
	}

	@Override
	public void startExercise() {
		is_run = true;
		callback.startBack();
		nodeList = new ArrayList<ExerciseNodeBean>();
		target_layout_setting.setVisibility(View.INVISIBLE);
		ThreadPoolUtils.execute(new TargetDJSThread());
	}

	@Override
	public void stopExercise() {
		is_run = false;
	}

	@Override
	public void selectPosition(int pos) {
		target_type_pos = pos;
		target_text_name.setText(targets[target_type_pos]);
		currentMax = max[target_type_pos];
	}

	@Override
	public void setSlope(float slope) {
		if (allow_change_in_running) {
			current_slope = slope;
		}
	}

	@Override
	public void setSpeed(float speed) {
		if (allow_change_in_running) {
			current_speed = Constants.SpeedConvertByKMH(speed);
		}
	}

	private ExerciseGroupBean getCumulativeData(int time) {
		ExerciseGroupBean groupBean = new ExerciseGroupBean();
		groupBean.setMaxNum(currentNum);
		/** 累计距离 */
		float distance = 0;
		float calorie;
		if (nodeList.size() == 0) {
			distance = (current_speed * time);
			groupBean.setAverageSlope(current_slope);
			groupBean.setAverageSpeed(current_speed);
		} else {
			float slopes = 0;
			ExerciseNodeBean bean = nodeList.get(0);
			int old_time = bean.getNodeTime();
			int current_time = old_time;
			distance = (bean.getNodeTime() * bean.getNodeSpeed());
			slopes = (bean.getNodeTime() * bean.getNodeSlope());
			for (int i = 1; i < nodeList.size(); i++) {
				bean = nodeList.get(i);
				current_time = bean.getNodeTime();
				distance = (distance + bean.getNodeSpeed()
						* (current_time - old_time));
				slopes = (slopes + bean.getNodeSlope()
						* (current_time - old_time));
				old_time = current_time;
			}
			distance = distance + (time - old_time) * current_speed;
			slopes = slopes + (time - old_time) * current_slope;
			groupBean.setAverageSlope(slopes / time);
			groupBean.setAverageSpeed(distance / time);
		}
		calorie = Constants.getKcal(distance);
		groupBean.setKeepTime(time);
		groupBean.setDistance(distance);
		groupBean.setCalorie(calorie);
		switch (target_type_pos) {
		case 0: {
			cumulativeNum = time;
		}
			break;
		case 1: {
			cumulativeNum = (int) distance;
		}
			break;
		case 2: {
			cumulativeNum = (int) calorie;
		}
			break;
		}
		return groupBean;
	}

	class TargetDJSThread implements Runnable {
		@Override
		public void run() {
			try {
				int time = 0;
				ExerciseGroupBean groupBean = new ExerciseGroupBean();
				/** 未主动停止锻炼且未完成设置目标 */
				while (is_run && cumulativeNum < currentNum) {
					/** 时间间隔1秒即重新计算累加 */
					Thread.sleep(1000);
					time++;
					/** 判断速度是否改变，改变记录时间节点 */
					if (current_speed != old_speed
							|| current_slope != old_slope) {
						nodeList.add(new ExerciseNodeBean(time, old_speed,
								old_slope));
						old_speed = current_speed;
						old_slope = current_slope;
					}
					/** 计算累计 */
					groupBean = getCumulativeData(time);
					/** 通知刷新 */
					callback.updateExercise(groupBean);
				}
				callback.stopBack(is_run, groupBean);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean checkInitComplete() {
		/** 根据是否设置目标成功 */
		if (!target_text_num.getText().toString().trim().equals("")) {
			isCanStart = true;
		} else {
			isCanStart = false;
		}
		return isCanStart;
	}

	class MyHandler extends Handler {
		public MyHandler(Looper looper) {
			super(looper);
		}

		public void handleMessage(Message msg) {
			show_test_info.setText(msg.obj.toString());

		}
	}

	@SuppressWarnings("unused")
	private void showTest(String x) {
		new MyHandler(Looper.getMainLooper()).sendMessage(NormalUtils
				.getMessage(0x001, x));
	}

	@Override
	public void onProgressChange(XSeekBar xSeekBar, int progress, boolean isUser) {
		this.progress = progress;
		int target = (int) (progress * currentMax / 100);
		switch (target_type_pos) {
		case 0: {
			currentNum = target * 60;
			target_text_num.setText(String.valueOf(target) + "  "
					+ NormalUtils.getString(targets_unit[target_type_pos]));
		}
			break;
		case 1: {
			currentNum = target * 10;
			target_text_num.setText(String.valueOf(Constants.keepDecimal(
					(float) currentNum / 1000.0f, 2))
					+ "  "
					+ NormalUtils.getString(targets_unit[target_type_pos]));
		}
			break;
		case 2: {
			currentNum = target;
			target_text_num.setText(String.valueOf(currentNum) + "  "
					+ NormalUtils.getString(targets_unit[target_type_pos]));
		}
			break;
		}
	}
	@Override
	public boolean checkIsCanSetSpeedSlope() {
		return true;
	}
}
